import {get, post} from "./axios.js";
import utils from "./utils";
import {Message} from 'element-ui'

const url = {
    findManyUserUrl: '/v1/user/findManyUser',
    registerUrl: '/v1/user/register',
    loginUrl: '/v1/user/login',
}

/**
 * 分页查询请求对象 query
 * @param filter
 * @param page
 * @param pageSize
 * @constructor
 */
export function query(filter = {}, page = 1, pageSize = 10) {
    let data = {
        filter: filter,
        page: page,
        page_size: pageSize,
    }
    return post(url.findManyUserUrl, data, {}, true, true)
}

/**
 * 注册
 * @param nickName
 * @param account
 * @param password
 * @param data
 * @returns {Promise<AxiosResponse<any>>}
 */
export function register(nickName, account, password, data) {
    if (utils.isEmpty(nickName, account, password, data.real_name, data.mail_address, data.position)) {
        Message({
            message: "请求失败，请检查所有必填项",
            type: "error"
        })
        return Promise.reject('request param err')
    } else {
        let data = {
            nick_name: nickName,
            account: account,
            password: password,
            data: {
                real_name: data.real_name,
                mail_address: data.mail_address,
                position: data.position,
                auth: data.auth,
            }
        }
        return post(url.registerUrl, data, {}, false, true)
    }
}

/**
 * login
 * @param account
 * @param password
 * @param router
 */
export function loginHandler(account, password, router) {
    if (utils.isEmpty(account, password)) {
        Message({
            message: "账号：root 密码：root",
            type: "error"
        })
        return false
    } else {
        let data = {account: account, password: password}
        post(url.loginUrl, data, {}, true, false)
            .then((response) => {
                if (response.data.code === 0) {
                    sessionStorage.setItem(utils.constPool.TOKEN, response.data.result.access_token);
                    sessionStorage.setItem(utils.constPool.NICKNAME, response.data.result.nick_name);
                    sessionStorage.setItem(utils.constPool.ACCOUNT, response.data.result.account);
                    router.push({path: `/main`})
                } else {
                    Message({
                        type: "warning",
                        message: response.data.msg,
                    });
                }
            })
    }

}

/**
 *
 */
export function update() {

}